package com.weiyuwqj.api.util;

import com.cunguanbao.api.utils.APIUtils;
import com.cunguanbao.api.utils.CoderException;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by hello on 2016/8/15.
 */
public class SignUtils {

    private static final String priKey = "r1r35cg+8els54jxi84n4-0dq72ep9bwox68mkoq7kdtp5-g0801r+bb8ocvn41l1g82v47r4idwln-shsvq7sholj2r2-h5m/3k4h5/da/-s+n+ellps87yj9j9rwgt56lvem8u-t-d0sst7f3z6vuoj-oiumsiwp62badfwyd7pwb03xl3q6tx5us/u/y/37n7yp-d172arzq6psfohdz41+rti38y6q0bnelhmy7d35bzw/nti-j4mnom58cou+3+tohef5e5nqsazq341/xmcdbny19rj--jqysvmn1zj-dflkszu83nm/6my5q-u+nlg9flyckh1eaux20ljpfwm3xrh70dmxiji8okesmzieb-1ew1en7biaj4ch29di37+340eichb+r21ifxqib8le4xl/gxkd/if87l13f5agl08arztxqai/l082h4nvrzl5ecn1lxg98/j39rz2xfjm2u3+y4lw/p+/cqg290b1m/hbp/5--f4wpse0eh";

    private static final String PUBLIC_KEY = "kl94bifcdmil6ash3wwpsp2z3usx71o9amphpv5f22b8x-u8fb5b-77-1sf9q6329+hhvigiiqsfp3i1yhp6krbi4vroj6iplju+dsyckivarq5wd9tal9xjjk5q4np584l66165j-snpzi2chec1drii2awh25nz55fme679dyhb8tsdktz12kg6bhuy1knpxcqpjhxw4g7mmi-sc4x1xn1dqsllcw5cpfpp6pbqcmbwa0exoj71s+sdnpcc0ou8z6zmyp-3zo4u9adhtyy2yi7jxtv81qorl8-aft14y236ol7r17in6hwel945zuhvkt2pyxtq231op56m4hbs+qtl59p2pe4jy60y23xxvpy-uc+ncyxxey6v8qatxwrj0u9egy3-u10kxfyalth5phzajbf6pixx+aik6jc7ykt27yij0+6wefx8+uej0rjjcdvlgswrt++nk8kao1b2zh8fsxudydglupx3mobr853h5+p";

    //public static String key ;

    private static final String RSA = "RSA";


    public static boolean toVerify(String key, String sign, Map params) {
        try {
            return APIUtils.verify(key, sign, params, "RSA");
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (CoderException e) {
            e.printStackTrace();
        }
        return false;
    }


    public static String toSign(String key, Map params) {
        String sign = null;
        params = sortMapByKey(params);

        try {
            sign = APIUtils.createSign(key, params, RSA);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (CoderException e) {
            e.printStackTrace();
        }
        return sign;
    }

    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, String> sortMap = new TreeMap<String, String>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }

    static class MapKeyComparator implements Comparator<String> {

        @Override
        public int compare(String str1, String str2) {

            return str1.compareTo(str2);
        }
    }

    /**
     * 签名，拿到signData（md5小写）
     *
     * @param data
     * @return
     */
    public static String getSignData(TreeMap data) {
        String result = "";
        Set<String> keys = data.keySet();
        for (String key : keys) {
            result = result + data.get(key) + "|";
        }
        result = result + priKey;
        String signData = null;
        try {
            signData = MD5.toMD5(result).toLowerCase();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return signData;
    }

    public static TreeMap getTreeMap(Map map) {
        TreeMap m = new TreeMap();
        for (Object o : map.keySet()) {
            m.put(o, map.get(o));
        }
        return m;
    }

    /**
     * 根据签名数据和请求参数
     * 拿到发post请求的参数
     *
     * @param data
     * @return
     */
    public static String getURLParam(TreeMap data) {
        String result = "";
        String signData = getSignData(data);
        Set<String> keys = data.keySet();
        for (String key : keys) {
            result = result + key + "=" + data.get(key) + "&";
        }
        result = result + "signdata=" + signData;
        return result;
    }

    /**
     * 根据签名数据和请求参数
     * 拿到发post请求的参数
     *
     * @param data
     * @return
     */
    public static Map getURLParamByMap(TreeMap data) {
        Map resultMap = new TreeMap();
        resultMap = data;
        String signData = getSignData(data);
        resultMap.put("signdata", signData);
        return resultMap;
    }

    public String getDataJsonString(TreeMap data) {
        String result = JsonUtils.toJson(data);
        result = "[" + result + "]";
        return result;
    }


}
